package org.jcnc.staffingsystem.stage;

import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import org.jcnc.staffingsystem.db.EmployeeManager;
import org.jcnc.staffingsystem.module.*;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.json.JSONObject;

import static org.jcnc.staffingsystem.list.OptionsManager.getPositionOptions;

/**
 * @author 许轲
 * Created on 2024/2/20$
 */
public class loginScene {
    static TextBox accountTextBox;
    public BorderPane getBorderPane() {
        BorderPane borderPane = new BorderPane();

        accountTextBox = new TextBox("账户");

        PasswordBox passwordTextBox = new PasswordBox("密码");
        ChoiceBox choiceBox = new ChoiceBox("权限", getPositionOptions(), "请选择");
        ButtonHBox buttonHBox = new ButtonHBox("登录", "注册");
        buttonHBox.setTwoAction(event -> {
            RegisterScene registerScene = new RegisterScene();
            registerScene.show();
            Stage stage = (Stage) borderPane.getScene().getWindow();
            stage.close();
        });

        buttonHBox.setOneAction(event -> {
            String username = accountTextBox.getText();
            String password = passwordTextBox.getText();

            JSONObject loginData = new JSONObject();
            loginData.put("username", username);
            loginData.put("password", password);

            try {
                URL url = new URL("http://localhost:8000/login");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);

                String data = "username=" + username + "&password=" + password;
                System.out.println(data);
                byte[] postData = data.getBytes(StandardCharsets.UTF_8);
                int postDataLength = postData.length;
                conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
                conn.getOutputStream().write(postData);

                int responseCode = conn.getResponseCode();
                System.out.println("Login Response Code: " + responseCode);


                if (responseCode == HttpURLConnection.HTTP_OK) {
                    Stage stage = (Stage) borderPane.getScene().getWindow();
                    stage.close();
                    new MainScene().show();



                } else {
                    System.out.println("登录失败!");
                }

                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });


        LoginBox loginBox = new LoginBox();
        loginBox.addLoginComponents(accountTextBox, passwordTextBox, choiceBox, buttonHBox);

        borderPane.setCenter(loginBox);
        return borderPane;
    }

    public static String getAccount() {
        return accountTextBox.getText();
    }
}
